﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HenrryTools.WinFormTools
{
    public partial class RequestWinForm : Form
    {
        /// <summary>
        /// 
        /// </summary>
        public static string ContentType { get; set; } = "application/json";
        public RequestWinForm()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 请求次数
        /// </summary>
        public int SendCount { set; get; } = 0;
        /// <summary>
        /// 定时请求信息累计
        /// </summary>
        public string SendMessage { set; get; }

        /// <summary>
        /// 调用保存
        /// </summary>
        public void GetSave()
        {
            //headers
            Dictionary<string, string> requestHeaders = new Dictionary<string, string>();
            int DGVHeadersCount = DGVHeaders.Rows.Count;
            if (DGVHeadersCount >= 2)
            {
                requestHeaders = GetHeadersValue(DGVHeadersCount);
            }
            //如果Params不为空，获取Params内容
            int DGVParamsCount = DGVParams.Rows.Count;
            string RootValue = null;
            if (DGVParamsCount >= 2)
            {
                RootValue = GetParamsValue(DGVParamsCount);
            }
            Properties.Settings.Default.RequestWinForm = cboxMethod.Text + "," + txtUrlRoot.Text + "," + txtBodyRoot.Text + "," + txtDataTime.Text + "," + cobTime.Text;//保存在Settings
            Properties.Settings.Default.RequesHeaderstWinForm = JsonConvert.SerializeObject(requestHeaders);
            Properties.Settings.Default.RequesParmastWinForm = JsonConvert.SerializeObject(RootValue);
            Properties.Settings.Default.Save();//保存
        }
        /// <summary>
        /// 运行按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRequest_Click(object sender, EventArgs e)
        {
            ThreadStart threadstart = () => //声明和定义线程委托，
            {
               State();//多线程待调用方法1
            };
            Common.HenrryHelper.ThreadWithCallBack(threadstart);//多线程调用带回调
        }
        public void State() {
            btnRequest.Text = "请求中";
            btnRequest.Enabled = false;
            StartEndTimes.Enabled = false;
            WaitForm1 waitForm1 = new WaitForm1();
            waitForm1.ShowMessage();
            btnSendAsync(0);
            GetSave();
            waitForm1.HideMessage();
            btnRequest.Enabled = true;
            StartEndTimes.Enabled = true;
            btnRequest.Text = "运行";
        }
        /// <summary>
        /// 执行请求
        /// </summary>
        private void btnSendAsync(int IsTimeRequest)
        {
            //如果请求方法和url为空则提示
            if (string.IsNullOrEmpty(txtUrlRoot.Text) || string.IsNullOrEmpty(cboxMethod.Text)) { MessageBox.Show("请求的URL为空!"); return; }
            DGVHeaders.EndEdit();//解决DataGuidView退出编辑状态以保存数值
            DGVParams.EndEdit();//解决DataGuidView退出编辑状态以保存数值
            //判断请求方法
            switch (cboxMethod.Text)
            {
                case "POST":
                    RequestPost(IsTimeRequest);
                    break;
                case "GET":
                    RequestPut(IsTimeRequest);
                    break;
                case "PUT":
                    break;
                default:
                    RequestPost(IsTimeRequest);
                    break;
            }
        }

        /// <summary>
        /// 请求GET
        /// </summary>
        private  void RequestPut(int IsTimeRequest)
        {
            //Headers的入参
            Dictionary<string, string> requestHeaders = new Dictionary<string, string>();
            int DGVHeadersCount = DGVHeaders.Rows.Count;
            try
            {
                //如果headers不为空，获取headers内容
                if (DGVHeadersCount >= 2)
                {
                    requestHeaders = GetHeadersValue(DGVHeadersCount);
                }

                //DGVParams的入参
                int DGVParamsCount = DGVParams.Rows.Count;
                string RootValue = null;
                //如果Params不为空，获取Params内容
                if (DGVParamsCount >= 2)
                {
                    RootValue = GetParamsValue(DGVParamsCount);
                }

                string UrlRoot = string.Format("{0}{1}", txtUrlRoot.Text, RootValue != null ? "?" + RootValue : null);
                string response = Common.HttpHelper.CreateRequestWithGET(UrlRoot, requestHeaders.Count < 1 ? null : requestHeaders, null, Encoding.UTF8, ContentType, null);
                if (response == null) { txtMessages.Text = "请求异常，无返回值";  }
                try
                {
                    object obj = JsonConvert.DeserializeObject(response);
                    //var jo = obj as JObject;
                    //labMessageCode.Text ="Status:"+ jo["status"].Value<string>();
                    //如果请求code不是200则给颜色区分
                    //if (labMessageCode.Text=="200") {
                    labMessageCode.ForeColor = Color.SpringGreen;
                    //}
                    //else {
                    //    labMessageCode.ForeColor = Color.Red;
                    //}
                    //获取入参返回
                    //如果是定时请求
                    if (IsTimeRequest == 0)
                    {
                        txtMessages.Text = JsonConvert.SerializeObject(obj);
                    }
                    else
                    {
                        SendMessage += "当前请求第" + SendCount + "次，返回值为:" + JsonConvert.SerializeObject(obj) + "\n";
                        txtMessages.Text = SendMessage;
                    }
                }
                catch (Exception ex)
                {
                    txtMessages.Text = response + ex.Message;
                }
            }
            catch (Exception ex)
            {
                txtMessages.Text = ex.Message;
                txtMessages.ForeColor = Color.Red;
            }
        }
        /// <summary>
        ///  //如果Params不为空，获取Params内容
        /// </summary>
        /// <param name="dGVParamsCount"></param>
        /// <returns></returns>
        private string GetParamsValue(int dGVParamsCount)
        {
            string RootText = null;
            for (var i = 0; i < dGVParamsCount - 1; i++)
            {
                string Key = null; string Value = null;
                for (var j = 0; j < 2; j++)
                {
                    if (j == 0 && DGVParams.Rows[i].Cells[j].Value != null) Key = DGVParams.Rows[i].Cells[j].Value.ToString();
                    if (j == 1 && DGVParams.Rows[i].Cells[j].Value != null) Value = DGVParams.Rows[i].Cells[j].Value.ToString();
                }
                if (Key != null && Value != null) RootText += Key + "=" + Value;
                if (Key != null && Value != null && i != dGVParamsCount - 1) RootText += "&";
            }
            return RootText;
        }

        /// <summary>
        /// 请求Post的方法
        /// </summary>
        private string RequestPost(int IsTimeRequest)
        {
            try
            {
                //Headers的入参
                Dictionary<string, string> requestHeaders = new Dictionary<string, string>();
                //requestHeaders.Add("Postman-Token", "<calculated when request is sent>");
                //requestHeaders.Add("Content-Type", "application/json");
                //requestHeaders.Add("Content-Length", "<calculated when request is sent>");
                //requestHeaders.Add("Host", "<calculated when request is sent>");
                //requestHeaders.Add("User-Agent", "PostmanRuntime/7.28.4");
                //requestHeaders.Add("Accept", "*/*");
                //requestHeaders.Add("Accept-Encoding", "gzip, deflate, br");
                //requestHeaders.Add("Connection", "keep-alive");

                //获取dataGuidview插件Headers的总行数
                int DGVHeadersCount = DGVHeaders.Rows.Count;
                //如果headers不为空，获取headers内容
                if (DGVHeadersCount >= 2)
                {
                    requestHeaders = GetHeadersValue(DGVHeadersCount);
                }
                //获取Body的入参
                byte[] dataRoot = txtBodyRoot.Text != null ? Encoding.UTF8.GetBytes(txtBodyRoot.Text) : null;
                string UrlRoot = string.Format("{0}", txtUrlRoot.Text);
                string response = Common.HttpHelper.CreateRequestWithPOST(UrlRoot, requestHeaders.Count < 1 ? null : requestHeaders, dataRoot, Encoding.UTF8, ContentType, null);
                if (response == null) { txtMessages.Text = "请求异常，无返回值"; return null; }
                try
                {
                    object obj = JsonConvert.DeserializeObject(response);
                    //var jo = obj as JObject;
                    //labMessageCode.Text ="Status:"+ jo["status"].Value<string>();
                    //如果请求code不是200则给颜色区分
                    //if (labMessageCode.Text=="200") {
                    labMessageCode.ForeColor = Color.SpringGreen;
                    //}
                    //else {
                    //    labMessageCode.ForeColor = Color.Red;
                    //}
                    //获取入参返回
                    //如果是定时请求
                    if (IsTimeRequest == 0)
                    {
                        txtMessages.Text = JsonConvert.SerializeObject(obj);
                    }
                    else
                    {
                        SendMessage += "当前请求第" + SendCount + "次，返回值为:" + JsonConvert.SerializeObject(obj) + "\n";
                        txtMessages.Text = SendMessage;
                    }
                }
                catch (Exception ex)
                {
                    txtMessages.Text = response + ex.Message;
                }

            }
            catch (Exception ex)
            {
                txtMessages.Text = ex.Message;
                txtMessages.ForeColor = Color.Red;
            }
            return null;
        }
        //如果headers不为空，获取headers内容
        private Dictionary<string, string> GetHeadersValue(int dGVHeadersCount)
        {
            Dictionary<string, string> requestHeaders = new Dictionary<string, string>();
            for (var i = 0; i < dGVHeadersCount - 1; i++)
            {
                string Key = null; string Value = null;
                for (var j = 0; j < 2; j++)
                {
                    if (j == 0 && DGVHeaders.Rows[i].Cells[j].Value != null) Key = DGVHeaders.Rows[i].Cells[j].Value.ToString();
                    if (j == 1 && DGVHeaders.Rows[i].Cells[j].Value != null) Value = DGVHeaders.Rows[i].Cells[j].Value.ToString();
                }
                if (Key != null && Value != null) requestHeaders.Add(Key, Value);
            }
            return requestHeaders;
        }
        /// <summary>
        /// 定时器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick_1(object sender, EventArgs e)
        {
            btnSendAsync(1);
            labMessageCode.Text = "请求次数:" + SendCount++;
            labMessageCode.ForeColor = Color.Red;
        }


        private void StartEndTimes_Click(object sender, EventArgs e)
        {
            if (StartEndTimes.Text == "开始定时请求")
            {
                if (string.IsNullOrEmpty(txtDataTime.Text)) { MessageBox.Show("设置定时运行时间为空!"); return; }
                SendMessage = null;
                int DataTime = 0;
                switch (cobTime.Text)
                {
                    case "毫秒":
                        DataTime = int.Parse(txtDataTime.Text);
                        break;
                    case "秒":
                        DataTime = int.Parse(txtDataTime.Text) * 1000;
                        break;
                    case "分":
                        DataTime = int.Parse(txtDataTime.Text) * 1000 * 60;
                        break;
                    case "时":
                        DataTime = int.Parse(txtDataTime.Text) * 1000 * 60 * 60;
                        break;
                    case "天":
                        DataTime = int.Parse(txtDataTime.Text) * 1000 * 60 * 60 * 24;
                        break;
                    case "周":
                        DataTime = int.Parse(txtDataTime.Text) * 1000 * 60 * 60 * 24 * 7;
                        break;
                    case "月":
                        DataTime = int.Parse(txtDataTime.Text) * 1000 * 60 * 60 * 24 * 30;
                        break;
                    default:
                        DataTime = int.Parse(txtDataTime.Text) * 1000;
                        break;
                }
                timer1.Interval = DataTime;
                timer1.Enabled = true;
                StartEndTimes.Text = "关闭定时请求";
            }
            else
            {
                timer1.Enabled = false;
                StartEndTimes.Text = "开始定时请求";
                SendCount = 0;
            }
            GetSave();
        }
        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RequestWinForm_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(Properties.Settings.Default.RequestWinForm))
            {
                string[] Values = Properties.Settings.Default.RequestWinForm.Split(',');
                cboxMethod.Text = Values[0];
                txtUrlRoot.Text = Values[1];
                txtBodyRoot.Text = Values[2];
                cobTime.Text = Values[4];

            }
            if (!string.IsNullOrWhiteSpace(Properties.Settings.Default.RequesHeaderstWinForm))
            {
                var HeadersValues = JsonConvert.DeserializeObject(Properties.Settings.Default.RequesHeaderstWinForm);
                int nember = 0;
                if (HeadersValues == null) return;
                foreach (var item in HeadersValues as JObject)
                {
                    DGVHeaders.Rows.Add();
                    DGVHeaders.Rows[nember].Cells[0].Value = item.Key;
                    DGVHeaders.Rows[nember].Cells[1].Value = item.Value;
                    nember++;
                }
            }
            if (!string.IsNullOrWhiteSpace(Properties.Settings.Default.RequesParmastWinForm))
            {
                var ParmstValues = JsonConvert.DeserializeObject(Properties.Settings.Default.RequesParmastWinForm);
                int nember = 0;
                if (ParmstValues==null) return;
                foreach (var item in ParmstValues as JObject)
                {
                    DGVParams.Rows.Add();
                    DGVParams.Rows[nember].Cells[0].Value = item.Key;
                    DGVParams.Rows[nember].Cells[1].Value = item.Value;
                    nember++;
                }
            }
        }
    }
}
